/**
 * Main application activity.
 * This is the screen displayed when you open the application
 * 
 * Copyright (C) 2009-2011  Rodrigo Zechin Rosauro
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Zechin Rosauro
 * @version 1.0
 */

package com.zhongketech.sunflower.droidwall;

import java.util.Arrays;
import java.util.Comparator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.R;
import com.zhongketech.sunflower.activity.BaseActivity;
import com.zhongketech.sunflower.droidwall.Api.DroidApp;

/**
 * Main application activity.
 * This is the screen displayed when you open the application
 */
@SuppressLint("HandlerLeak")
public class DroidWallHandle{

	// Menu options
	private static final int MENU_DISABLE	= 0;
	private static final int MENU_TOGGLELOG	= 1;
	private static final int MENU_APPLY		= 2;
	private static final int MENU_EXIT		= 3;
	private static final int MENU_HELP		= 4;
	private static final int MENU_SHOWLOG	= 5;
	private static final int MENU_SHOWRULES	= 6;
	private static final int MENU_CLEARLOG	= 7;
	private static final int MENU_SETPWD	= 8;
	private static final int MENU_SETCUSTOM = 9;

	private static final String defaultMode = Api.MODE_WHITELIST;

	/** progress dialog instance */
	private ListView listview = null;
	/** indicates if the view has been modified and not yet saved */
	private boolean dirty = false;

	/** Called when the activity is first created. */

	private static Context context = null;
	private static DroidWallHandle instance = null;

	private DroidWallHandle()
	{}

	synchronized public static DroidWallHandle getInstance(Context ctx)
	{
		if(context != ctx)
		{
			context = ctx;
			instance = new DroidWallHandle();
		}

		return instance;
	}

	public boolean enableNetLock()
	{
		if(Api.isEnabled(context))
		{
			return true;
		}
		
		MyToast.getInstance().show("家长开启了断网控制");
		selectMode(Api.MODE_WHITELIST);
		Api.setEnabled(context, true);
		applyOrSaveRules();
		return true;
	}
	
	public boolean diableNetLockForced()
	{
//		selectMode(Api.MODE_BLACKLIST);
//		if(Api.isEnabled(context))
//		{
			MyToast.getInstance().show("强制关掉断网控制");
			Api.setEnabled(context, false);
			purgeRules();
			refreshHeader();
			applyOrSaveRules();
//		}

		return true;
	}

	public boolean diableNetLock()
	{
//		selectMode(Api.MODE_BLACKLIST);
		if(Api.isEnabled(context))
		{
			MyToast.getInstance().show("家长关闭了断网控制");
			Api.setEnabled(context, false);
			purgeRules();
			refreshHeader();
			applyOrSaveRules();
		}

		return true;
	}

	/**
	 * Check if the stored preferences are OK
	 */
	private void checkPreferences() {
		final SharedPreferences prefs = context.getSharedPreferences(Api.PREFS_NAME, 0);
		final Editor editor = prefs.edit();
		boolean changed = false;
		if (prefs.getString(Api.PREF_MODE, "").length() == 0) {
			editor.putString(Api.PREF_MODE, Api.MODE_WHITELIST);
			changed = true;
		}
		/* delete the old preference names */
		if (prefs.contains("AllowedUids")) {
			editor.remove("AllowedUids");
			changed = true;
		}
		if (prefs.contains("Interfaces")) {
			editor.remove("Interfaces");
			changed = true;
		}
		if (changed) editor.commit();
	}
	/**
	 * Refresh informative header
	 */
	private void refreshHeader() {
		final SharedPreferences prefs = context.getSharedPreferences(Api.PREFS_NAME, 0);
		final String mode = prefs.getString(Api.PREF_MODE, Api.MODE_WHITELIST);
		//		final TextView labelmode = (TextView) this.findViewById(R.id.label_mode);
		//		final Resources res = getResources();
		int resid = (mode.equals(Api.MODE_WHITELIST) ? R.string.mode_whitelist : R.string.mode_blacklist);
		//		labelmode.setText(res.getString(R.string.mode_header, res.getString(resid)));
		//		resid = (Api.isEnabled(this) ? R.string.title_enabled : R.string.title_disabled);
		//		setTitle("向日葵联网控制");
	}


	private void selectMode(final String mode)
	{
		//    	final Resources res = getResources();
		//    	new AlertDialog.Builder(this).setItems(new String[]{res.getString(R.string.mode_whitelist),res.getString(R.string.mode_blacklist)}, new DialogInterface.OnClickListener(){
		//			public void onClick(DialogInterface dialog, int which) {
		//final String mode = (which==0 ? Api.MODE_WHITELIST : Api.MODE_BLACKLIST);
		final SharedPreferences sharedPreferences = context.getSharedPreferences(Api.PREFS_NAME, 0);	
		final String oriMode = sharedPreferences.getString(Api.PREF_MODE, Api.MODE_WHITELIST);
		if(null != mode && !mode.equals(oriMode))
		{
			final Editor editor = sharedPreferences.edit();
			editor.putString(Api.PREF_MODE, mode);
			editor.commit();
			refreshHeader();
		}

		//			}
		//    	}).setTitle("Select mode:")
		//    	.show();
	}

	private void toggleLogEnabled() {
		final SharedPreferences prefs = context.getSharedPreferences(Api.PREFS_NAME, 0);
		final boolean enabled = !prefs.getBoolean(Api.PREF_LOGENABLED, false);
		final Editor editor = prefs.edit();
		editor.putBoolean(Api.PREF_LOGENABLED, enabled);
		editor.commit();
		if (Api.isEnabled(context)) {
			Api.applySavedIptablesRules(context, true);
		}
		Toast.makeText(context, (enabled?R.string.log_was_enabled:R.string.log_was_disabled), Toast.LENGTH_SHORT).show();
	}

	/**
	 * Enables or disables the firewall
	 */
	private void disableOrEnable() {
		final boolean enabled = !Api.isEnabled(context);
		Log.d("DroidWall", "Changing enabled status to: " + enabled);
		Api.setEnabled(context, enabled);
		if (enabled) {
			applyOrSaveRules();
		} else {
			purgeRules();
		}
		refreshHeader();
	}

	private void enable()
	{
		final boolean enabled = Api.isEnabled(context);

		if (enabled) {
			Log.d("DroidWall", "is enable ...");
		} else {
			Api.setEnabled(context, true);
			applyOrSaveRules();	
		}

		refreshHeader();
	}

	/**
	 * Apply or save iptable rules, showing a visual indication
	 */
	private void applyOrSaveRules() {
		//		final Resources res = getResources();
		final boolean enabled = Api.isEnabled(context);
		//		final ProgressDialog progress = ProgressDialog.show(this, res.getString(R.string.working), res.getString(enabled?R.string.applying_rules:R.string.saving_rules), true);
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				//				try {progress.dismiss();} catch(Exception ex){}
				if (enabled) {
					Log.d("DroidWall", "Applying rules.");
					if (Api.hasRootAccess(context, true) && Api.applyIptablesRules(context, true)) {
						Toast.makeText(context, R.string.rules_applied, Toast.LENGTH_SHORT).show();
					} else {
						Log.d("DroidWall", "Failed - Disabling firewall.");
						Api.setEnabled(context, false);
					}
				} else {
					Log.d("DroidWall", "Saving rules.");
					Api.saveRules(context);
					Toast.makeText(context, R.string.rules_saved, Toast.LENGTH_SHORT).show();
				}
				DroidWallHandle.this.dirty = false;
			}
		};
		handler.sendEmptyMessageDelayed(0, 100);
	}
	/**
	 * Purge iptable rules, showing a visual indication
	 */
	private void purgeRules() {
		//		final Resources res = getResources();
		//		final ProgressDialog progress = ProgressDialog.show(this, res.getString(R.string.working), res.getString(R.string.deleting_rules), true);
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				//				try {progress.dismiss();} catch(Exception ex){}
				if (!Api.hasRootAccess(context, true)) return;
				if (Api.purgeIptables(context, true)) {
					Toast.makeText(context, R.string.rules_deleted, Toast.LENGTH_SHORT).show();
				}
			}
		};
		handler.sendEmptyMessageDelayed(0, 100);
	}
}
